Swadhin Biswas feat(api): add runner, analytics, packages, and security services · 3/6/2026
28f7954
193 lines · 6.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import { logger } from "@/lib/logger";
import { getDatabase, schema } from "@/db";
import { validateBasicAuth } from "@/lib/auth-basic";
import { canReadRepo, canWriteRepo } from "@/lib/permissions";
import { resolveRepoPath, releaseRepo, parseStoragePath } from "@/lib/git-storage";
import type { APIRoute } from "astro";
import { spawn } from "child_process";
import { and, eq } from "drizzle-orm";
import { PassThrough, Readable } from "stream";

export const ALL: APIRoute = async ({ params, request }) => {
  const { owner: ownerName, repo: repoName, path } = params;

  if (!ownerName || !repoName || !path) {
    return new Response("Not Found", { status: 404 });
  }

  const db = getDatabase();

  // 1. Fetch Repo
  const user = await db.query.users.findFirst({
    where: eq(schema.users.username, ownerName),
  });

  if (!user) return new Response("Not Found", { status: 404 });

  const repoData = await db.query.repositories.findFirst({
    where: and(
      eq(schema.repositories.ownerId, user.id),
      eq(schema.repositories.name, repoName)
    ),
  });

  if (!repoData) return new Response("Not Found", { status: 404 });

  // 2. Auth Check
  const authHeader = request.headers.get("Authorization");
  logger.info(`[GitBackend] Auth check for ${ownerName}/${repoName}: authHeader=${authHeader ? 'present' : 'missing'}`);
  let userId: string | null = null;
  if (authHeader) {
    userId = await validateBasicAuth(authHeader);
    logger.info(`[GitBackend] Auth result: userId=${userId || 'null'}`);
  }

  // 3. Handle Routes
  const url = new URL(request.url);
  const service = url.searchParams.get("service");

  // Get local path (downloads from R2 if needed)
  let localRepoPath: string;
  try {
    localRepoPath = await resolveRepoPath(repoData.diskPath);
  } catch (err) {
    logger.error("Failed to resolve repo path:", err);
    return new Response("Internal Server Error", { status: 500 });
  }

  // --- info/refs ---
  if (path === "info/refs") {
    if (!service)
      return new Response("Dumb HTTP protocol not supported", { status: 403 });

    const isUpload = service === "git-upload-pack";
    const isReceive = service === "git-receive-pack";

    if (!isUpload && !isReceive)
      return new Response("Forbidden", { status: 403 });

    // Check permissions
    let hasAccess = false;
    if (isUpload) {
      hasAccess = await canReadRepo(userId || undefined, repoData);
    } else {
      hasAccess = await canWriteRepo(userId || undefined, repoData);
    }

    if (!hasAccess) {
      return new Response("Unauthorized", {
        status: 401,
        headers: { "WWW-Authenticate": 'Basic realm="OpenCodeHub"' },
      });
    }

    const cmd = service.replace("git-", "");
    const child = spawn("git", [
      cmd,
      "--stateless-rpc",
      "--advertise-refs",
      localRepoPath,
    ]);

    const stream = new PassThrough();

    // Packet line
    const serviceLine = `# service=${service}\n`;
    const len = (serviceLine.length + 4).toString(16).padStart(4, "0");
    stream.write(`${len}${serviceLine}0000`);

    child.stdout.pipe(stream);

    // Log errors
    child.stderr.on("data", (data) => {
      logger.error(`Git error (${service}):`, data.toString());
    });

    return new Response(stream as any, {
      headers: {
        "Content-Type": `application/x-${service}-advertisement`,
        "Cache-Control": "no-cache",
      },
    });
  }

  // --- git-upload-pack / git-receive-pack ---
  if (path === "git-upload-pack" || path === "git-receive-pack") {
    if (request.method !== "POST")
      return new Response("Method Not Allowed", { status: 405 });

    const isUpload = path === "git-upload-pack";

    // Check permissions
    let hasAccess = false;
    if (isUpload) {
      hasAccess = await canReadRepo(userId || undefined, repoData);
    } else {
      hasAccess = await canWriteRepo(userId || undefined, repoData);
    }

    if (!hasAccess) {
      return new Response("Unauthorized", {
        status: 401,
        headers: { "WWW-Authenticate": 'Basic realm="OpenCodeHub"' },
      });
    }

    const cmd = path.replace("git-", "");
    const child = spawn("git", [cmd, "--stateless-rpc", localRepoPath]);

    if (request.body) {
      // Convert Web Stream to Node Stream
      const nodeStream = Readable.fromWeb(request.body as any);
      nodeStream.pipe(child.stdin);
    } else {
      child.stdin.end();
    }

    // Log errors
    child.stderr.on("data", (data) => {
      logger.error(`Git error (${path}):`, data.toString());
    });

    // Handle process exit
    child.on("close", async (code) => {
      if (code === 0) {
        // Trigger Analysis on successful push
        // Trigger Analysis on successful push
        if (!isUpload) { // git-receive-pack
          try {
            logger.info(`[GitBackend] Push successful, triggering analysis for ${ownerName}/${repoName}`);

            // Trigger Analysis FIRST (while files are still locally present)
            const { analyzeRepository } = await import("@/lib/analysis");
            await analyzeRepository(repoData.id, userId).catch((err) => {
              logger.error(`[GitBackend] Analysis failed for ${ownerName}/${repoName}:`, err);
            });
            logger.info(`[GitBackend] Analysis completed for ${ownerName}/${repoName}`);
          } catch (err) {
            logger.error("Failed to trigger analysis after push:", err);
          } finally {
            // SYNC BACK TO R2 (Upload and Cleanup)
            // Always run this even if analysis fails
            try {
              await releaseRepo(ownerName, repoName, true);
              logger.info(`Synced ${ownerName}/${repoName} back to R2 after push`);
            } catch (cleanupErr) {
              logger.error(`[GitBackend] Failed to clean up ${ownerName}/${repoName}:`, cleanupErr);
            }
          }
        }
      }
    });

    return new Response(child.stdout as any, {
      headers: {
        "Content-Type": `application/x-${path}-result`,
        "Cache-Control": "no-cache",
      },
    });
  }

  return new Response("Not Found", { status: 404 });
};